<template>
  <el-dialog :title="currentForm.orderUuid ? '修改临时用车' : '创建临时用车'" :model-value="dialog" @close="close">
    <el-form :model="formData" :rules="rules" ref="uploadForm" label-width="auto" style="padding: 0 20px" class="Dform">
      <div v-if="userStore.accountType != 2">
        <el-form-item label="品牌" prop="brandUuid">
          <el-select v-model="formData.brandUuid" @change="getSeriesList(true)" filterable clearable style="width: 100%"
            placeholder="请选择品牌">
            <el-option v-for="item in brandList" :key="item.brandUuid" :label="item.brandName"
              :value="item.brandUuid" />
          </el-select>
        </el-form-item>
        <el-form-item label="车系" prop="seriesUuid">
          <el-select v-model="formData.seriesUuid" @change="getModelList(true)" filterable clearable style="width: 100%"
            placeholder="请选择车系">
            <el-option v-for="item in seriesList" :key="item.seriesUuid" :label="item.seriesName"
              :value="item.seriesUuid" />
          </el-select>
        </el-form-item>
        <el-form-item label="车型" prop="modelUuid">
          <el-select v-model="formData.modelUuid" filterable clearable style="width: 100%" placeholder="请选择车型">
            <el-option v-for="item in modelList" :key="item.modelUuid" :label="item.modelName"
              :value="item.modelUuid" />
          </el-select>
        </el-form-item>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="车型类型" prop="modelType">
            <el-select v-model="formData.modelType" filterable clearable style="width: 100%" placeholder="请选择车型类型">
              <el-option v-for="item in priceModelTypeMap.keys()" :key="item" :label="priceModelTypeMap.get(item)"
                :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单类型" prop="orderType">
            <el-select v-model="formData.orderType" @change="orderTypeChange" filterable clearable style="width: 100%"
              placeholder="请选择订单类型">
              <el-option v-for="item in orderTypeMap.keys()" :key="item" :label="orderTypeMap.get(item)"
                :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <el-form-item label="包车时间(小时)" prop="hours" v-if="formData.orderType == 7">
          <el-input v-model="formData.hours" type="number" />
        </el-form-item>
        <el-form-item label="航班号" prop="flightNumber" v-if="formData.orderType == 2">
          <el-input v-model="formData.flightNumber" />
        </el-form-item>
        <el-form-item label="车次号" prop="trainNumber" v-if="formData.orderType == 4">
          <el-input v-model="formData.trainNumber" />
        </el-form-item>
        <el-form-item label="路线" prop="route" v-if="formData.orderType == 7">
          <el-input v-model="formData.route" />
        </el-form-item>
        <el-row v-if="formData.orderType != 7">
          <el-col :span="12">
            <el-form-item label="出发地" prop="departureAddress">
              <el-input v-model="formData.departureAddress" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目的地" prop="destinationAddress">
              <el-input v-model="formData.destinationAddress" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-row v-if="userStore.accountType == 1">
        <el-col :span="12">
          <el-form-item label="价格（元）" prop="price">
            <el-input v-model="formData.price" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="司机价格" prop="driverShowPrice">
            <el-input v-model="formData.driverShowPrice" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="用车单位" prop="useCarPartner" v-if="userStore.accountType == 1">
        <el-input v-model="formData.useCarPartner" placeholder="请输入用车单位" />
      </el-form-item>
      <el-form-item label="城市" prop="cityCode">
        <area-code v-model:province="formData.province" v-model:provinceCode="formData.provinceCode"
          v-model:city="formData.city" v-model:cityCode="formData.cityCode" />
      </el-form-item>
      <el-form-item label="订单时间" prop="serviceStartTimeStr">
        <el-date-picker v-model="formData.serviceStartTimeStr" type="datetime" value-format="YYYY-MM-DD HH:mm"
          style="width: 100%" format="YYYY-MM-DD HH:mm" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="乘客姓名" prop="passengerName">
            <el-input v-model="formData.passengerName" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="乘客手机号" prop="passengerMobile">
            <el-input v-model="formData.passengerMobile" type="number" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-select v-model="formData.remark" multiple filterable clearable allow-create default-first-option
          :reserve-keyword="false" placeholder="输入后回车可添加新备注" style="width: 100%">
          <el-option v-for="v in options" :key="v" :label="v" :value="v" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
        <el-button v-if="!formData.orderUuid" @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { brandQueryAll, selectListByBrandUuid, selectListBySeriesUuid, carQuery } from '@/api/vehicle'
import AreaCode from '@/components/area-code/index.vue'
import { updateOrder, createTempOrder, queryOrderDetail } from "@/api/order"
import { partnerQuery, } from '@/api/user'
import { orderStatusMap, orderTypeMap, priceModelTypeMap } from '@/config/constants'
import { validateMobile } from '@/utils'

import { useUserStore } from '@/stores'

export default defineComponent({
  components: {},
  props: {
    dialog: {
      type: Boolean,
      default: false,
    },
    currentForm: {
      type: Object,
      default: () => { },
    },
    selectMenuList: {
      type: Array as PropType<{ title: string; id: string | number }[]>,
      default: () => [],
    },
  },
  emits: ['update:currentForm', 'update:dialog', 'refresh'],
  setup(props, context) {
    const formData = reactive(props.currentForm)
    const uploadForm = ref<any>(null)
    const userStore = useUserStore()
    const brandList = ref<any>([])
    const seriesList = ref<any>([])
    const modelList = ref<any>([])
    const partnerList = ref<any>([])
    // const carList = ref<any>([])
    // const driverList = ref<any>([])
    const priceConfigList = ref<any>([])
    const priceConfig = ref<any>({})
    const options = ref<any>([
      '车辆整洁',
      '正装出行',
      '矿泉水',
    ])

    watch(() => props.dialog,
      (val) => {
        Object.assign(formData, props.currentForm)
        if (formData.remark) {
          formData.remark = formData.remark.split('，')
        }
        console.log(formData)
      }
    )
    const orderTypeChange = (val: any) => {
      options.value = ['车辆整洁', '正装出行', '矿泉水']
      formData.remark = [...options.value]
      // 送机
      if (val == 2) {
        options.value.push('举牌接机')
        // formData.remark = options.value
      } else if (val == 1) {
        // 接机
        options.value.push('立即联系客人')
        formData.remark = [...options.value]
      }
    }

    const close = () => {
      context.emit('update:dialog', false)
      context.emit('refresh', { ...formData })
      context.emit('update:currentForm', {})
    }

    const priceConfigChange = (val: any) => {
      priceConfig.value = priceConfigList.value.find((item: any) => item.priceConfigUuid == val) || {}
    }

    const getSeriesList = (flag = false) => {
      if (flag) {
        formData.seriesUuid = ''
        formData.modelUuid = ''
        formData.carUuid = ''
      }
      if (!formData.brandUuid) {
        return
      }
      selectListByBrandUuid({ pageNum: 1, pageSize: 100, brandUuid: formData.brandUuid }).then((res: any) => {
        seriesList.value = res.data || []
      })
    }

    const getModelList = (flag = false) => {
      if (flag) {
        formData.modelUuid = ''
        formData.carUuid = ''
      }
      if (!formData.seriesUuid) {
        return
      }
      selectListBySeriesUuid({ pageNum: 1, pageSize: 100, seriesUuid: formData.seriesUuid }).then((res: any) => {
        modelList.value = res.data || []
      })
    }

    const getDetail = () => {
      queryOrderDetail({ orderUuid: props.currentForm.orderUuid }).then((res: any) => {
        if (res.code === 200) {
          let data = res.data.data
          Object.assign(formData, { ...data.orderSnapshotResponse, ...data.driverResponse })
          if (formData.remark) {
            formData.remark = formData.remark.split('，')
          }
          if (formData.brandUuid) {
            getSeriesList()
          }
          if (formData.seriesUuid) {
            getModelList()
          }
          // detailData.value = res.data.data.orderSnapshotResponse
          // driverInfo.value = res.data.data.driverResponse
        } else {
          ElMessage.error(res.message || '获取订单详情失败')
        }
      })
    }

    onMounted(() => {

      partnerQuery({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
        partnerList.value = res.data.list || []
      })

      brandQueryAll().then((res: any) => {
        brandList.value = res.data || []
      })
      if (props.currentForm.orderUuid) {
        getDetail()
      }
    })

    const onSubmit = () => {
      uploadForm.value.validate((valid: boolean) => {
        if (valid) {
          if (formData.orderUuid) {
            updateOrder({ ...formData, remark: formData.remark.join('，') }).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('修改成功')
                close()
              }
            })
          } else {
            createTempOrder({ ...formData, remark: formData.remark.join('，') }).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('添加成功')
                close()
              }
            })
          }
        } else {
          ElMessage({
            message: '验证失败',
            type: 'error',
            duration: 1000,
          })
          return false
        }
      })
    }

    const resetForm = () => {
      uploadForm.value.resetFields()
      context.emit('update:currentForm', {})
    }

    return {
      uploadForm,
      formData,
      // carList,
      priceConfigList,
      priceModelTypeMap,
      brandList,
      seriesList,
      modelList,
      //driverList,
      partnerList,
      userStore,
      options,
      orderTypeChange,
      orderStatusMap,
      orderTypeMap,
      priceConfigChange,
      getSeriesList,
      getModelList,
      priceConfig,
      close,
      resetForm,
      onSubmit,
      // getCarList,
      rules: {
        // carUuid: [
        //   { required: true, message: '请选择车辆', trigger: 'blur' }
        // ],
        // driverUuid: [
        //   { required: true, message: '请选择司机', trigger: 'blur' }
        // ],
        brandUuid: [
          { required: true, message: '请选择品牌', trigger: 'blur' }
        ],
        seriesUuid: [
          { required: true, message: '请选择车系', trigger: 'blur' }
        ],
        modelUuid: [
          { required: true, message: '请选择车型', trigger: 'blur' }
        ],
        modelType: [
          { required: true, message: '请选择车型类型', trigger: 'blur' }
        ],
        hours: [
          { required: true, message: '请输入包车时间(小时)', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        driverShowPrice: [
          { required: true, message: '请输入司机价格', trigger: 'blur' }
        ],
        // passengerName: [
        //   { required: true, message: '请输入乘客姓名', trigger: 'blur' }
        // ],
        passengerMobile: [
          {
            validator: (rule: any, value: string, callback: any) => {
              if (value && !(/^(?:(?:\+|00)86)?1\d{10}$/.test(value))) {
                callback(new Error('请输入正确的乘客手机号'))
              } else {
                callback()
              }
            }
          }
        ],
        serviceStartTimeStr: [
          { required: true, message: '请选择订单开始时间', trigger: 'blur' }
        ],
        orderType: [
          { required: true, message: '请选择订单类型', trigger: 'blur' }
        ],
        priceConfigUuid: [
          { required: true, message: '请选择价格配置', trigger: 'blur' }
        ],
        trainNumber: [
          { required: true, message: '请输入车次号', trigger: 'blur' }
        ],
        cityCode: [
          { required: true, message: '请选择城市', trigger: 'blur' }
        ],
        flightNumber: [
          { required: true, message: '请输入航班号', trigger: 'blur' }
        ],
        // route: [
        //   { required: true, message: '请输入路线', trigger: 'blur' }
        // ],
        departureAddress: [
          { required: true, message: '请输入出发地', trigger: 'blur' }
        ],
        destinationAddress: [
          { required: true, message: '请输入目的地', trigger: 'blur' }
        ],
        useCarPartner: [
          { required: true, message: '请选择用车合作方', trigger: 'blur' }
        ],
        // orderStatus: [
        //   { required: true, message: '请选择订单状态', trigger: 'blur' }
        // ],
      },
    }
  },
})
</script>

<style></style>
